<template>
  <div class="category-products">
    <div class="page-header">
      <h2>商品分类</h2>
      <el-breadcrumb separator="/">
        <!-- <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item> -->
        <el-breadcrumb-item :to="{ path: '/official/index' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品分类</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <!-- 商品筛选 -->
    <div class="filter-section">
      <el-form :inline="true" :model="queryParams" class="filter-form">
        <el-form-item label="价格区间">
          <el-input-number v-model="queryParams.minPrice" :min="0" placeholder="最低价" style="width: 130px"/>
          <span class="separator">-</span>
          <el-input-number v-model="queryParams.maxPrice" :min="0" placeholder="最高价" style="width: 130px"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery" icon="el-icon-search">查询</el-button>
          <el-button @click="resetQuery" icon="el-icon-refresh">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 调试信息 -->
    <div v-if="isLoading" class="loading-message">
      <el-alert title="正在加载商品数据..." type="info" :closable="false"></el-alert>
    </div>

    <!-- 数据状态调试 -->
<!--    <div v-if="!isLoading && productList.length === 0" class="debug-info">
      <el-alert title="当前未获取到商品数据，请检查控制台日志" type="warning" :closable="false">
        <div>请确保：</div>
        <ol>
          <li>URL中包含正确的type参数</li>
          <li>后端API返回正确的数据格式</li>
          <li>网络连接正常</li>
        </ol>
      </el-alert>
    </div>-->

    <div class="products-grid">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :md="8" :lg="6" v-for="item in productList" :key="item.id">
          <div class="product-card-wrapper">
            <el-card :body-style="{ padding: '0px' }" class="product-card" shadow="hover">
              <div class="product-image-container">
                <img :src="item.imageUrl || defaultImage" class="product-image" alt="商品图片" @error="handleImageError">
                <div class="product-tag" v-if="item.isNew">新品</div>
                <div class="product-stock" v-if="item.stockQuantity">库存: {{item.stockQuantity}}件</div>
              </div>
              <div class="product-info">
                <div class="product-brand" v-if="item.brand">{{item.brand}}</div>
                <h3 class="product-title" :title="item.name">{{ item.name }}</h3>
                <div class="product-price" v-if="isValidPrice(item.unitPrice)">
                  ¥<span class="price-value">{{ formatPrice(item.unitPrice) }}</span>
                </div>
                <div class="product-price" v-else-if="isValidPrice(item.price)">
                  ¥<span class="price-value">{{ formatPrice(item.price) }}</span>
                </div>
                <div class="product-price" v-else>
                  ¥<span class="price-value price-missing">请询价</span>
                </div>
                <div class="product-footer">
                  <el-button type="danger" size="mini" round @click="viewDetail(item.id)" icon="el-icon-view">查看详情</el-button>
                </div>
              </div>
            </el-card>
          </div>
        </el-col>
      </el-row>

      <div v-if="!productList.length && !isLoading" class="empty-state">
        <el-empty description="暂无商品数据">
          <el-button type="primary" @click="getList" icon="el-icon-refresh">重新加载</el-button>
        </el-empty>
      </div>

      <div class="pagination-container" v-if="total > 0">
        <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="queryParams.pageNum"
            :page-sizes="[12, 24, 36, 48]"
            :page-size="queryParams.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
        />
      </div>
    </div>
  </div>
</template>

<script>
import {getProductList} from '@/api/supply/type'; // 只需获取商品列表

export default {
  name: 'CategoryProducts',
  data() {
    return {
      queryParams: {
        pageNum: 1,
        pageSize: 12,
        status: 1,
        type: null, // 使用 type 来表示分类标识符
        minPrice: null,
        maxPrice: null,
        supplierName: null,
      },
      productList: [],
      total: 0,
      isLoading: false,
      defaultImage: require('@/assets/images/default.png'), // 默认图片
    };
  },
  created() {
    // 从路由中获取 'type' 参数
    const type = this.$route.query.type;
    console.log("路由参数 type:", type); // 调试输出
    if (type) {
      this.queryParams.type = parseInt(type); // 使用 'type' 作为分类标识符
      this.getList(); // 页面加载时根据 type 获取该分类下的商品列表
    } else {
      this.$message.warning('未找到分类参数，请从分类页面进入');
    }
  },
  methods: {
    // 格式化价格显示
    formatPrice(price) {
      // 调试输出价格值
      console.log("原始价格值:", price, "类型:", typeof price);

      if (price === null || price === undefined) return '0.00';

      // 尝试转换为数字
      let numericPrice = price;
      if (typeof price === 'string') {
        numericPrice = parseFloat(price);
      }

      // 再次检查转换后的值是否为有效数字
      if (isNaN(numericPrice) || numericPrice === 0) {
        console.warn("价格转换失败或为0:", price);
        return '0.00';
      }

      // 使用toFixed确保小数点后两位
      return numericPrice.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
    },
    // 获取该分类下的商品列表
    async getList() {
      console.log("Query Params: ", this.queryParams); // 调试输出
      if (!this.queryParams.type) {
        console.warn("缺少分类参数，无法获取商品列表");
        this.productList = [];
        this.total = 0;
        return;
      }
      this.isLoading = true;
      try {
        const response = await getProductList(this.queryParams);
        console.log("API完整响应:", response); // 调试输出，查看API返回的具体数据结构

        if (!response) {
          throw new Error('API没有返回数据');
        }

        // 判断响应中是否直接包含rows和total
        if (response.rows && Array.isArray(response.rows)) {
          this.productList = response.rows;
          this.total = response.total || 0;
        }
        // 如果是完整的响应，包含code、msg、rows和total
        else if (response.code === 0 && response.rows && Array.isArray(response.rows)) {
          this.productList = response.rows;
          this.total = response.total || 0;
        }
        // 查找响应中的可能数据结构
        else {
          console.warn("尝试查找可能的数据结构");
          let found = false;

          // 遍历对象查找可能的数组数据
          for (const key in response) {
            if (Array.isArray(response[key])) {
              console.log(`发现可能的商品数据数组在 ${key} 字段中`);
              this.productList = response[key];
              found = true;
              if (response.total) {
                this.total = response.total;
              } else {
                this.total = this.productList.length;
              }
              break;
            }
          }

          // 如果没有找到数组，检查是否有嵌套结构
          if (!found && typeof response === 'object') {
            for (const key in response) {
              if (response[key] && typeof response[key] === 'object') {
                if (Array.isArray(response[key].rows)) {
                  console.log(`在嵌套对象 ${key} 中找到商品数据数组`);
                  this.productList = response[key].rows;
                  this.total = response[key].total || this.productList.length;
                  found = true;
                  break;
                }
              }
            }
          }

          // 如果上述都失败，尝试直接查看第一层的每个键
          if (!found) {
            console.warn("无法自动识别数据结构，请检查API响应格式");
            console.log("响应的所有键:", Object.keys(response));
          }
        }

        // 检查商品数据中的价格字段
        if (this.productList.length > 0) {
          // 输出第一个商品的全部属性，用于调试
          const firstProduct = this.productList[0];
          console.log("第一个商品的完整数据:", firstProduct);

          // 遍历所有商品，确保价格字段存在且为正确类型
          this.productList.forEach((item, index) => {
            // 添加新品标记
            if (index % 3 === 0) {
              item.isNew = true;
            }

            // 检查价格字段
            console.log(`商品[${index}] ID:${item.id}, 名称:${item.name}, 价格:${item.unitPrice}, 类型:${typeof item.unitPrice}`);

            // 如果unitPrice不存在但price存在，使用price
            if ((item.unitPrice === undefined || item.unitPrice === null) && item.price !== undefined && item.price !== null) {
              console.log(`商品[${index}] 使用替代价格字段 price: ${item.price}`);
              item.unitPrice = item.price;
            }
          });
        } else {
          console.warn("未获取到商品数据");
        }
      } catch (error) {
        this.$message.error('获取商品列表失败，请稍后重试');
        console.error('获取商品列表出错:', error);
        this.productList = [];
        this.total = 0;
      } finally {
        this.isLoading = false;
        console.log("处理完成后的商品列表长度:", this.productList.length);
      }
    },
    handleQuery() {
      if (this.queryParams.minPrice && this.queryParams.maxPrice && this.queryParams.minPrice > this.queryParams.maxPrice) {
        this.$message.warning('最低价不能高于最高价');
        return;
      }
      this.queryParams.pageNum = 1;
      this.getList(); // 重新查询该分类下的商品列表
    },
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 12,
        type: this.queryParams.type, // 保留当前分类
        minPrice: null,
        maxPrice: null,
        supplierName: null,
      };
      this.getList(); // 重置查询条件并重新获取该分类下的商品列表
    },
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.queryParams.pageNum = 1;
      this.getList(); // 更新每页显示商品数并重新获取商品列表
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.getList(); // 切换页码并重新获取商品列表
    },
    viewDetail(id) {
      window.open(`/supply/prodinfo/${id}`, '_blank');
    },
    // 处理图片加载错误
    handleImageError(e) {
      console.error('图片加载失败，使用默认图片替代');
      e.target.src = this.defaultImage;
    },
    isValidPrice(price) {
      return price !== undefined && price !== null && !isNaN(parseFloat(price)) && parseFloat(price) > 0;
    },
  },
};

</script>

<style scoped>
.category-products {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
  background: #f9f9f9;
}

.page-header {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 15px;
  border-bottom: 2px solid #f0f0f0;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #333;
  position: relative;
  padding-left: 12px;
}

.page-header h2::before {
  content: '';
  position: absolute;
  left: 0;
  top: 5px;
  height: 16px;
  width: 4px;
  background: #1890ff;
  border-radius: 2px;
}

.filter-section {
  margin-bottom: 20px;
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.filter-form .separator {
  margin: 0 10px;
  color: #999;
}

.loading-message,
.debug-info {
  margin-bottom: 15px;
}

.products-grid {
  margin-top: 20px;
}

.product-card-wrapper {
  margin-bottom: 24px;
  transition: all 0.3s;
}

.product-card {
  height: 100%;
  border: none;
  overflow: hidden;
  transition: all 0.3s;
}

.product-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1) !important;
}

.product-image-container {
  position: relative;
  height: 220px;
  overflow: hidden;
}

.product-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.6s;
}

.product-card:hover .product-image {
  transform: scale(1.05);
}

.product-tag {
  position: absolute;
  top: 10px;
  right: 0;
  background-color: #C03639;
  color: white;
  padding: 2px 10px;
  font-size: 12px;
  border-top-left-radius: 12px;
  border-bottom-left-radius: 12px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.product-stock {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: rgba(0, 0, 0, 0.6);
  color: white;
  padding: 4px 8px;
  font-size: 12px;
  text-align: center;
}

.product-info {
  padding: 16px;
  background: #fff;
}

.product-brand {
  font-size: 12px;
  color: #666;
  margin-bottom: 6px;
  padding: 0 4px;
  display: inline-block;
  border-radius: 2px;
  background-color: #f0f0f0;
}

.product-title {
  font-size: 15px;
  margin: 0 0 12px 0;
  height: 42px;
  line-height: 21px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  color: #333;
  font-weight: 500;
}

.product-price {
  color: #C03639;
  font-size: 14px;
  font-weight: normal;
  margin: 12px 0;
}

.price-value {
  font-size: 20px;
  font-weight: bold;
  margin-left: 2px;
}

.price-missing {
  font-size: 16px;
  color: #888;
  font-style: italic;
  font-weight: normal;
}

.product-footer {
  text-align: center;
  padding-top: 10px;
  margin-top: 10px;
  border-top: 1px dashed #eee;
}

.pagination-container {
  text-align: center;
  margin-top: 40px;
  margin-bottom: 20px;
}

.empty-state {
  margin: 40px 0;
  padding: 30px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

@media (max-width: 768px) {
  .product-image-container {
    height: 180px;
  }

  .product-title {
    font-size: 14px;
    height: 38px;
    line-height: 19px;
  }

  .product-price {
    font-size: 13px;
  }

  .price-value {
    font-size: 18px;
  }
}
</style>
